<template>
  <ele-page flex-table>
    <ComHeader :title="`盘点单详情[${info?.order_sn}]`" @back="goBack" />
    <ele-bottom-bar v-if="!['YD', 'CD'].includes(info.status)" :teleported="true">
      <template #extra>
        <el-button v-if="info.is_cd === 1" type="info" @click="onCommand('CD')">取消订单</el-button>
        <el-button v-if="info.is_ed === 1" type="primary" plain @click="onCommand('EDIT')">编辑</el-button>
        <el-button v-if="info.is_pd === 1" type="primary" plain @click="onCommand('PD')">开始盘点</el-button>
        <el-button v-if="info.is_tj === 1" type="primary" plain @click="onCommand('TJ')">提交</el-button>
        <el-button v-if="info.is_qr === 1" type="primary" plain @click="onCommand('QR')">确认</el-button>
        <el-button v-if="info.is_yd === 1" type="primary" plain @click="onCommand('YD')">审核</el-button>
      </template>
    </ele-bottom-bar>

    <ele-card flex-table bordered :header-style="{ padding: '0 16px' }">
      <el-scrollbar>
        <el-descriptions title="单据详情" :column="4">
          <el-descriptions-item label="单据编号">{{ info.order_sn }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ info.status_name }}</el-descriptions-item>
          <el-descriptions-item label="商品数">{{ info.product_num }}</el-descriptions-item>
          <el-descriptions-item label="单据日期">{{ info.order_date }}</el-descriptions-item>
          <el-descriptions-item label="平台">{{ info.mch_name }}</el-descriptions-item>
          <el-descriptions-item v-if="info.supplier_name" label="货主">{{ info.supplier_name }}</el-descriptions-item>
          <el-descriptions-item label="仓库">{{ info.warehouse_name }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ info.create_user_name }}</el-descriptions-item>
          <el-descriptions-item label="创建日期">{{ formatDate(info.create_time) }}</el-descriptions-item>
        </el-descriptions>
        <ele-pro-table
          v-show="false"
          ref="proTableRef"
          :columns="columns"
          :datasource="info.product"
        />
        <el-descriptions class="mt-20px" title="商品信息" :column="4">
          <template #extra>
            <el-space :size="15">
              <el-button type="" plain @click="onPrint">打印</el-button>
              <el-button type="" plain @click="onExport">导出</el-button>
              <el-button v-if="info.is_tj === 1" class="" type="primary" plain @click="showEdit = true">添加商品</el-button>
            </el-space>
          </template>
        </el-descriptions>

        <el-table :data="info.product" stripe border>
          <el-table-column type="index" label="序" width="50" align="center" />
          <el-table-column prop="product_name" label="商品名称" min-width="140" />
          <el-table-column prop="product_code" label="商品编码" align="center" />

          <el-table-column
            prop="num"
            label="盘点数量"
            align="center"
            :width="Math.max(...info.product.map(v => v.multi_unit?.length), 1) * 110 + 60"
          >
            <template #default="{ row }">
              <div v-if="form.product_id === row.product_id" class="flex-a">
                <el-space>
                  <el-input
                    v-for="(item, i) in form.multi_unit"
                    :key="i"
                    v-model="item.num"
                    size="small"
                    class="w-100px!"
                    placeholder="数量"
                    oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                  >
                    <template #suffix><span class="text-#333!">{{ item.unit }}</span></template>
                  </el-input>
                </el-space>
                <div v-if="form.multi_unit?.length > 1" class="flex-shrink-0 min-w-60px ml-4px text-left">
                  = {{ totalUnit(form.multi_unit) }}{{ form.unit }}
                </div>
              </div>
              <div v-else>
                {{ row.num }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="location_name" label="盘点库位" align="center">
            <template #default="{ row }">
              <el-cascader
                v-if="form.product_id === row.product_id"
                v-model="form.location_id"
                class="w-full"
                :options="locationTree"
                filterable
                clearable
                size="small"
                placeholder="请选择库位"
                :show-all-levels="false"
                :props="{ value: 'id', label: 'name', expandTrigger: 'hover', emitPath: false }"
              />
              <div v-else>{{ row.location_name }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="diff_num" label="差异数量" align="center" />
          <el-table-column prop="stock" label="库存数量" align="center" />
          <el-table-column prop="unit" label="主单位" align="center" />
          <el-table-column v-if="info.is_tj === 1" label="操作" width="140" align="center">
            <template #default="{ row }">
              <el-link v-if="form.product_id === row.product_id" type="success" @click="save">保存</el-link>
              <el-link v-else type="primary" @click="openEdit(row)">编辑</el-link>
              <el-divider class="mx-10px" direction="vertical" />
              <el-popconfirm title="确定删除此项吗?" @confirm="remove(row)">
                <template #reference>
                  <el-link type="danger">删除</el-link>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </ele-card>

    <PageEdit
      v-model="showEdit"
      :orderId="orderId"
      :locationList="locationList"
      :warehouseId="info.warehouse_id"
      @done="getInfo"
    />
    <PageReview v-model="showReview" :statusList="[{ value: 'YD', label: '过账' }, { value: 'PD', label: '再盘点' }]" remarkDisabled @done="review" />
  </ele-page>
</template>

<script setup>
import { listWlList } from '@/api/common'
import PageReview from '@/components/Common/Review.vue'
import { toTree } from 'ele-admin-plus/es'

import PageEdit from './edit.vue'

const showEdit = ref(false)

const orderId = ref(0)
const route = useRoute()
const router = useRouter()
const { routeTabKey, removePageTab, setPageTabTitle } = utils.usePageTab()
const { formatDate, totalUnit } = utils
const info = ref({ product: [] })
const form = ref({})

const showReview = ref(false)
const proTableRef = ref(null)

const { addPageTab } = utils.usePageTab()

/** 表格列配置 */
// const columns2 = computed(() => {
//   const arr = [
//     {
//       type: 'index',
//       label: '序',
//       width: 50,
//       align: 'center',
//       fixed: 'left',
//     },
//     {
//       prop: 'product_name',
//       label: '商品名称',
//       minWidth: 160,
//       align: 'left',
//     },
//     {
//       prop: 'product_code',
//       label: '商品编码',
//       minWidth: 100,
//       align: 'center',
//     },
//     {
//       prop: 'num',
//       label: '盘点数量',
//       width: Math.max(...info.value.product.map(v => v.multi_unit?.length), 1) * 110 + 60,
//       align: 'center',
//       slot: 'num',
//     },
//     {
//       prop: 'location_name',
//       label: '盘点库位',
//       width: 180,
//       align: 'center',
//       slot: 'location_name',
//     },
//     {
//       prop: 'diff_num',
//       label: '差异数量',
//       minWidth: 80,
//       align: 'center',
//     },
//     {
//       prop: 'stock',
//       label: '库存数量',
//       minWidth: 80,
//       align: 'center',
//     },
//     {
//       prop: 'unit',
//       label: '主单位',
//       minWidth: 80,
//       align: 'center',
//     },
//   ]
//   if (info.value.is_tj) {
//     arr.push({
//       columnKey: 'action',
//       label: '操作',
//       width: 140,
//       align: 'center',
//       slot: 'action',
//       fixed: 'right',
//     })
//   }
//   return arr
// })

const columns = computed(() => {
  return [
    {
      columnKey: 'header',
      label: `盘点单：${info.value.order_sn}`,
      align: 'center',
      children: [
        {
          type: 'index',
          label: '序',
          width: 50,
          align: 'center',
        },
        {
          prop: 'product_name',
          label: '商品名称',
          width: 200,
          align: 'left',
        },
        {
          prop: 'product_code',
          label: '商品编码',
          width: 120,
          align: 'center',
        },
        {
          prop: 'num',
          label: '盘点数量',
          width: 100,
          align: 'center',
          formatter: row => utils.Big(row.num).eq(0) ? '' : `${row.num}${row.unit}`,
        },
        {
          prop: 'multi_unit',
          label: '数量明细',
          width: 120,
          align: 'center',
          formatter: (row) => {
            const list = row.multi_unit.filter(t => t.num > 0)
            return list.length ? list.map(v => `${v.num}${v.unit}`).join('、') : ''
          },
        },
        {
          prop: 'location_name',
          label: '盘点库位',
          width: 120,
          align: 'center',
        },
        {
          prop: 'diff_num',
          label: '差异数量',
          width: 100,
          align: 'center',
        },
        {
          prop: 'stock',
          label: '库存数量',
          width: 100,
          align: 'center',
        },
        {
          prop: 'unit',
          label: '主单位',
          width: 100,
          align: 'center',
        },
      ],
    },
  ]
})

function onPrint() {
  proTableRef.value?.printData?.({
    data: info.value.product,
  })
}

function onExport() {
  proTableRef.value?.exportData?.({
    fileName: `盘点单${info.value.order_sn}`,
    data: info.value.product,
  })
}

onMounted(() => {
  orderId.value = Number(route.params?.id)
  getInfo()
})

function goBack() {
  removePageTab({ key: routeTabKey })
  router.push('/stock/inventory')
}

function getInfo() {
  utils.get('/stockInventory/info', { id: orderId.value }).then((res) => {
    info.value = res.data
    if (!locationList.value.length) {
      getLocList(res.data.warehouse_id)
    }
    setPageTabTitle(`盘点单[${utils.ellipsisStr(res.data.order_sn, 0, 10)}]`)
  })
}

function review(data, cb) {
  updateStatus({
    id: info.value.id,
    status: data.status,
  }, cb)
}

function updateStatus(formData, cb) {
  const loading = utils.message('请求中..', 'loading')
  utils.post('/stockInventory/review', formData).then((res) => {
    utils.message(res.msg, res.success)
    if (res.success) {
      showReview.value = false
      getInfo()
    }
  }).finally(() => {
    cb && cb()
    loading.close()
  })
}

function onCommand(command) {
  const id = info.value.id

  if (command === 'EDIT') {
    const path = `/stock/inventory/edit/${id}`

    addPageTab({
      key: path,
      closable: true,
    })
    router.push(path)
  }
  else if (command === 'CD') {
    utils.confirm('确定要<span class="px-2px text-danger font-semibold">取消</span>盘点单吗', '系统提示', {
      type: 'warning',
      dangerouslyUseHTMLString: true,
      cancelButtonText: '不取消了',
      confirmButtonText: '确定取消',
    }).then(() => {
      updateStatus({ id, status: 'CD' })
    })
  }
  else if (command === 'YD') {
    showReview.value = true
  }
  else {
    // YS 审核通过 NS 审核不通过 FS 反审 OK 已结单
    const list = [
      { key: 'PD', title: '开始盘点' },
      { key: 'TJ', title: '提交' },
      { key: 'QR', title: '确认' },
    ]
    const item = list.find(v => v.key === command)
    utils.confirm(`确定要<span class="px-2px text-danger font-semibold">${item.title}</span>订单吗`, '系统提示', {
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }).then(() => {
      const formData = {
        id,
        status: command,
      }
      updateStatus(formData)
    })
  }
}

function openEdit(row) {
  form.value = row
  // if (row.location_id) {
  //   getLocList2()
  // }
  // else {
  //   locationTree.value = locationTreeFull.value
  //   form.value.location_id = undefined
  // }
  getLocList2()
}

const locationList = ref([])
const locationTree = ref([])
const locationTreeFull = ref([])

function getLocList(warehouseId) {
  listWlList(warehouseId).then((res) => {
    locationList.value = res.data
    locationTreeFull.value = toTree({
      data: res.data,
      idField: 'id',
      parentIdField: 'pid',
    })
  })
}

function getLocList2() {
  utils.get('/stockInventory/productToLocation', { warehouse_id: info.value.warehouse_id, product_id: form.value.product_id, level: 2 }).then((res) => {
    locationTree.value = toTree({
      data: res.data,
      idField: 'id',
      parentIdField: 'pid',
    })
    if (!res.data.some(v => v.id === form.value.location_id)) {
      form.value.location_id = undefined
    }
  })
}

function save() {
  utils.post('/stockInventory/addProduct', {
    id: orderId.value,
    product_id: form.value.product_id,
    location_id: form.value.location_id,
    num: totalUnit(form.value.multi_unit),
    multi_unit: form.value.multi_unit,
  }).then((res) => {
    utils.message(res.msg, res.success)
    if (res.success) {
      getInfo()
    }
    form.value = {}
  })
}

function remove(row) {
  utils.post('/stockInventory/delProduct', {
    id: orderId.value,
    product_id: row.product_id,
  }).then((res) => {
    utils.message(res.msg, res.success)
    if (res.success) {
      form.value = {}
      getInfo()
    }
  })
}
</script>

<style lang="scss" scoped></style>
